//
//  OutMailDetailViewController.m
//  Utils
//
//  Created by enghou on 2018/6/11.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "OutMailDetailViewController.h"
#import "NetWorkerManager.h"
#import "MediaItemModel.h"
#import "ScrollAddImageView.h"
#import <TZImagePickerController.h>
#import "WechatShortVideoController.h"
#import "AudioViewController.h"
#import "ReceiverChooseViewController.h"
#import "SmallGroupItemModel.h"
#import "LevelItemModel.h"
#import "InStationContactItemModel.h"
#import "MSSBrowseNetworkViewController.h"
#import "VideoViewController.h"
#import "PlayAudioViewController.h"
@interface OutMailDetailViewController ()<ShowImagePicker,HandleAudio,WechatShortVideoDelegate,UITextViewDelegate,UITextFieldDelegate,TotalProtocol>

@property (weak, nonatomic) IBOutlet UITextField *sendDateLbl;

@property (weak, nonatomic) IBOutlet UITextView *receiverLbl;

@property (weak, nonatomic) IBOutlet UITextField *titleLbl;

@property (weak, nonatomic) IBOutlet UITextView *contentLbl;

@property(nonatomic,strong)NSMutableArray *userIds;

@property(nonatomic,strong)NSMutableArray *groupIds;

@property(nonatomic,strong)NSMutableArray *orgIds;

@property(nonatomic,strong)NSMutableArray *filePaths;


@property (weak, nonatomic) IBOutlet ScrollAddImageView *fileCollection;


@property(nonatomic,strong)UIDatePicker *datePicker;
@end

@implementation OutMailDetailViewController{
    ReceiverChooseViewController *receiver;
}

-(instancetype)init{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"OutMailSearch" bundle:[NSBundle mainBundle]];
    return [story instantiateViewControllerWithIdentifier:@"OutMailDetailViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.userIds = [NSMutableArray array];
    self.groupIds = [NSMutableArray array];
    self.orgIds = [NSMutableArray array];
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 240)];
    self.datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    self.datePicker.backgroundColor = [UIColor whiteColor];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    self.datePicker.date = [NSDate date];
    self.sendDateLbl.inputView = self.datePicker;
    self.sendDateLbl.inputAccessoryView = [self inputAccessView];
    self.fileCollection.delegate = self;
    if (self.ids) {
        self.sendDateLbl.enabled = NO;
        self.receiverLbl.userInteractionEnabled = NO;
        self.titleLbl.enabled = NO;
        self.contentLbl.userInteractionEnabled = NO;
        UIBarButtonItem *trash = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(delRecord)];
        trash.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItems = @[trash];
    }
}

-(void)setContent:(NSString *)content{
    _content = content;
    self.contentLbl.text = _content;
}

-(void)setMsgTitle:(NSString *)msgTitle{
    _msgTitle = msgTitle;
    self.titleLbl.text = _msgTitle;
}

-(void)setReceiverNames:(NSString *)receiverNames{
    _receiverNames = receiverNames;
    self.receiverLbl.text = receiverNames;
}

-(void)setSendDate:(NSString *)sendDate{
    _sendDate = sendDate;
    self.sendDateLbl.text = sendDate;
}

+ (NSDictionary<NSString *,id> *)modelCustomPropertyMapper{
    return @{@"msgTitle":@"title"};
}

-(void)addAction{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *sound = [UIAlertAction actionWithTitle:@"录音" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self recordAction];
    }];
    [alert addAction:sound];
    UIAlertAction *mov = [UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self videoAction];
    }];
    [alert addAction:mov];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"拍照或从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoAction];
    }];
    [alert addAction:photo];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    
    [self presentViewController:alert animated:YES completion:nil];
}


-(void)recordAction{
    AudioViewController *audioVC = [[AudioViewController alloc]init];
    audioVC.delegate = self;
    self.definesPresentationContext = YES;
    UIColor *color = [UIColor blackColor];
    audioVC.view.backgroundColor = [color colorWithAlphaComponent:0.5];
    audioVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:audioVC animated:NO completion:nil];
}

-(void)videoAction{
    WechatShortVideoController *video = [[WechatShortVideoController alloc]init];
    video.delegate = self;
    [self presentVC:video];
}

-(void)photoAction{
    if ([self.fileCollection.source count] < 3) {
        TZImagePickerController *tz = [[TZImagePickerController alloc]initWithMaxImagesCount:3 - self.fileCollection.source.count delegate:nil];
        tz.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            NSMutableArray *images = [NSMutableArray array];
            for (UIImage *photo in photos) {
                MediaItemModel *model = [[MediaItemModel alloc]init];
                model.image = photo;
                [images addObject:model];
            }
            [self.fileCollection feedImages:images];
        };
        [self presentViewController:tz animated:YES completion:nil];
    }else{
        [self alertSome:@"最多选3个资源"];
    }
}

-(void)showBigImageWithCurrentIndex:(NSInteger)cindex imageSource:(NSArray *)source{
    MediaItemModel *model = self.fileCollection.source[cindex];
    switch (model.type) {
        case Image:
        {
            NSMutableArray *browseItemArray = [[NSMutableArray alloc]init];
            MSSBrowseModel *m = [[MSSBrowseModel alloc]init];
            m.bigImageUrl = model.fileURL.absoluteString;
            [browseItemArray addObject:m];
            MSSBrowseNetworkViewController *bvc = [[MSSBrowseNetworkViewController alloc]initWithBrowseItemArray:browseItemArray currentIndex:0];
            bvc.presentVC = self.navigationController;
            [bvc showBrowseViewController];
        }
            break;
        case Video:
        {
            VideoViewController *video = [[VideoViewController alloc]init];
            video.url = model.fileURL;
            [self presentVC:video];
        }
            break;
        case Audio:
        {
            PlayAudioViewController *audio = [[PlayAudioViewController alloc]init];
            audio.url = model.fileURL;
            [self presentVC:audio];
        }
            break;
        case Document:
        {
            
        }
            break;
        default:
            break;
    }
}

-(void)showPicker{
    if ([self.ids length] == 0) {
        if (self.fileCollection.source.count < 3) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *sound = [UIAlertAction actionWithTitle:@"录音" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self recordAction];
            }];
            [alert addAction:sound];
            UIAlertAction *mov = [UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self videoAction];
            }];
            [alert addAction:mov];
            UIAlertAction *photo = [UIAlertAction actionWithTitle:@"拍照或从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self photoAction];
            }];
            [alert addAction:photo];
            
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:cancel];
            
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            [self alertSome:@"只能选3个媒体资源!"];
        }
    }
}

-(void)sureAction{
    [self.sendDateLbl resignFirstResponder];
    self.sendDateLbl.text = [[self.datePicker date]dateLineStrOnlyDay];
}

-(void)cancelAction{
    [self.view endEditing:YES];
}

#pragma mark - AddAndEdit Delegate
-(NSString *)detailPath{
    return @"/mobile/comprehensiveGovernance/outbox/getOutboxMessageDetails.action";
}

-(NSDictionary *)detailParam{
    return @{@"messageId":self.ids};
}

-(void(^)(NSDictionary *))configView{
    void(^config)(NSDictionary *);
    config = ^(NSDictionary *source){
        NSDictionary *data = source[@"data"];
        if ([data isKindOfClass:[NSDictionary class]]) {
            [self yy_modelSetWithJSON:data];
            self.title = @"发件详情";
            NSArray *files = data[@"files"];
            NSMutableArray *medias = [NSMutableArray array];
            for (NSDictionary *element in files) {
                MediaItemModel *m = [[MediaItemModel alloc]initWithSource:element];
                [medias addObject:m];
            }
            [self.fileCollection feedImages:medias];
        }
    };
    return config;
}

-(NSString *)addPath{
    return @"/mobile/comprehensiveGovernance/outbox/sendMessage.action";
}

-(NSDictionary *)addedParameter{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.contentLbl.text forKey:@"platformMessage.content"];
    [param setObject:self.titleLbl.text forKey:@"platformMessage.title"];
    if (self.userIds.count == 0 && self.groupIds.count == 0 && self.orgIds.count == 0) {
        [self alertSome:@"请至少选择一个收件人!"];
        return nil;
    }
    if (self.userIds.count > 0) {
        [param setObject:[self.userIds componentsJoinedByString:@","] forKey:@"userIds"];
    }
    if (self.groupIds.count > 0) {
        [param setObject:[self.groupIds componentsJoinedByString:@","] forKey:@"groupIds"];
    }
    if (self.orgIds.count > 0) {
        [param setObject:[self.orgIds componentsJoinedByString:@","] forKey:@"orgIds"];
    }
    if (self.filePaths.count > 0) {
        [param setObject:[self.filePaths componentsJoinedByString:@","] forKey:@"filePaths"];
    }
    return param;
}

-(void)addRecord{
    if (self.fileCollection.source.count > 0) {
        [self uploadFiles:nil successBlock:^(NSArray<MediaItemModel *> *files) {
            NSMutableArray *paths = [NSMutableArray array];
            for (MediaItemModel *model in files) {
                [paths addObject:model.fileURL.path];
            }
            [super addRecord];
        }];
    }
}

-(NSString *)refresh_not_name{
    return @"refresh_out_mail";
}

-(void)uploadFiles:(NSArray <NSData *>*)files successBlock:(void(^)(NSArray <MediaItemModel *>*))suc{
    
    [self beginLoading];
    __block NSInteger uploadedCount = 0;
    NSMutableArray *paths = [NSMutableArray array];
    for (MediaItemModel *model in self.fileCollection.source) {
        switch (model.type) {
            case Image:
            {
                NSData *data = UIImageJPEGRepresentation(model.image, 0.2);
                [[NetWorkerManager sharedInstance]uploadImageWithPath:kUploadFilePath parameter:nil files:@[data] fileName:@"file" suffix:@"jpg" completeBlock:^(NSDictionary *source) {
                    BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[MediaItemModel class]];
                    if (model.success) {
                        [paths addObject:model.list[0]];
                        uploadedCount++;
                        if (uploadedCount == self.fileCollection.source.count) {
                            [self endLoading];
                            if (suc) {
                                suc(paths);
                            }
                        }
                    }else{
                        [self alertSome:@"上传文件失败!"];
                    }
                } failBlock:^(NSInteger code) {
                    [self endLoading];
                    [self alertSome:kNetWorkFail];
                }];
            }
                break;
            case Audio:
            {//_fileURL    NSURL *    @"/Users/enghou/Library/Developer/CoreSimulator/Devices/309283FA-5466-4B29-9BE3-31F79DB0E6FD/data/Containers/Data/Application/39129D01-951F-4071-A1C4-1639CBC5FE9C/Documents/CWVoice/CWVoice550498294.wav"    0x0000600000086b30
                NSError *error = nil;
                NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:model.fileURL.path] options:NSDataReadingUncached error:&error];
                if (data) {
                    [[NetWorkerManager sharedInstance]uploadAudeoWithPath:kUploadFilePath parameter:nil files:@[data] fileName:@"file" suffix:@"wmv" completeBlock:^(NSDictionary *source) {
                        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[MediaItemModel class]];
                        if (model.success) {
                            [paths addObject:model.list[0]];
                            uploadedCount++;
                            if (uploadedCount == self.fileCollection.source.count) {
                                [self endLoading];
                                if (suc) {
                                    suc(paths);
                                }
                            }
                        }else{
                            [self alertSome:@"上传文件失败!"];
                        }
                    } failBlock:^(NSInteger code) {
                        [self endLoading];
                        [self alertSome:kNetWorkFail];
                    }];
                }
            }
                break;
            case Video:
            {
                NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:model.fileURL.path] options:NSDataReadingUncached error:nil];
                if (data) {
                    [[NetWorkerManager sharedInstance]uploadVideoWithPath:kUploadFilePath parameter:nil files:@[data] fileName:@"file" suffix:@"wmv" completeBlock:^(NSDictionary *source) {
                        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[MediaItemModel class]];
                        if (model.success) {
                            [paths addObject:model.list[0]];
                            uploadedCount++;
                            if (uploadedCount == self.fileCollection.source.count) {
                                [self endLoading];
                                if (suc) {
                                    suc(paths);
                                }
                            }
                        }else{
                            [self alertSome:@"上传文件失败!"];
                        }
                    } failBlock:^(NSInteger code) {
                        [self endLoading];
                        [self alertSome:kNetWorkFail];
                    }];
                }
            }
                break;
            default:
                break;
        }
    }
}

-(NSString *)delPath{
    return @"/mobile/comprehensiveGovernance/outbox/deleteOutboxMessageById.action";
}

-(NSDictionary *)delParameter{
    return @{@"messageId":self.ids};
}

#pragma mark - HandleAudio Delegate
-(void)handleAudioWithFilePath:(NSURL *)filepath{
    MediaItemModel *model = [[MediaItemModel alloc]init];
    model.fileURL = filepath;
    model.type = 2;
    model.image = [UIImage imageNamed:@"icon_audio"];
    [self.fileCollection feedImage:model];
}

-(void)finishWechatShortVideoCapture:(NSURL *)filePath{
    MediaItemModel *model = [[MediaItemModel alloc]init];
    model.fileURL = filePath;
    model.type = 3;
    model.image = [UIImage imageNamed:@"icon_video"];
    [self.fileCollection feedImage:model];
}

#pragma mark - UITextViewDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView{
    if (!receiver) {
        receiver = [[ReceiverChooseViewController alloc]init];
        receiver.theDelete = self;
    }
    receiver.selectedLevels = self.orgIds;
    receiver.selectedGroups = self.groupIds;
    receiver.selectedContacts = self.userIds;
    receiver.title = @"收件人选择";
    [self push:receiver];
    [textView resignFirstResponder];
}

#pragma mark - TotalProtocol
-(void)fetchArray:(NSArray *)array{
    NSArray *first = array.firstObject;
    NSMutableArray *nameArrays = [NSMutableArray array];
    self.userIds = [NSMutableArray array];
    [first enumerateObjectsUsingBlock:^(InStationContactItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![self.userIds containsObject:obj.memberBaseId]) {
            [self.userIds addObject:obj.memberBaseId];
            [nameArrays addObject:obj.memberName];
        }
    }];
    NSArray *second = array[1];
    self.groupIds = [NSMutableArray array];
    [second enumerateObjectsUsingBlock:^(SmallGroupItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![self.groupIds containsObject:obj.ID]) {
            [self.groupIds addObject:obj.ID];
            [nameArrays addObject:obj.name];
        }
    }];
    NSArray *third = array.lastObject;
    self.orgIds = [NSMutableArray array];
    [third enumerateObjectsUsingBlock:^(SubLevelItemModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![self.orgIds containsObject:obj.ID]) {
            [self.orgIds addObject:obj.ID];
            [nameArrays addObject:obj.name];
        }
    }];
    NSString *names = [nameArrays componentsJoinedByString:@","];
    self.receiverLbl.text = names;
}

@end
